import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.table.DefaultTableModel;

public class BorrowPanel extends JPanel {
    private JTable borrowTable;
    private DefaultTableModel tableModel;
    private BookDAO bookDAO = new BookDAO();
    private ReaderDAO readerDAO = new ReaderDAO();
    private BorrowDAO borrowDAO = new BorrowDAO();

    public BorrowPanel() {
        setLayout(new BorderLayout());

        // 创建顶部面板，包含借阅和归还按钮
        JPanel topPanel = new JPanel(new BorderLayout());
        JButton borrowButton = new JButton("借阅图书");
        JButton returnButton = new JButton("归还图书");
        JButton refreshButton = new JButton("刷新");

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(borrowButton);
        buttonPanel.add(returnButton);
        buttonPanel.add(refreshButton);

        topPanel.add(buttonPanel, BorderLayout.WEST);

        // 创建表格
        String[] columnNames = {"ID", "图书ID", "图书名称", "读者ID", "读者姓名", "借阅日期", "应还日期", "归还日期", "状态"};
        tableModel = new DefaultTableModel(columnNames, 0);
        borrowTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(borrowTable);

        // 添加组件到面板
        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);

        // 初始化表格数据
        loadBorrows();

        // 添加按钮事件监听器
        borrowButton.addActionListener(e -> showBorrowDialog());

        returnButton.addActionListener(e -> {
            int selectedRow = borrowTable.getSelectedRow();
            if (selectedRow != -1) {
                int borrowId = (int) tableModel.getValueAt(selectedRow, 0);
                String status = (String) tableModel.getValueAt(selectedRow, 8);

                if ("已归还".equals(status)) {
                    JOptionPane.showMessageDialog(BorrowPanel.this, "该图书已归还", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                int confirm = JOptionPane.showConfirmDialog(BorrowPanel.this,
                        "确定要归还这本书吗?", "确认归还", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    if (borrowDAO.returnBook(borrowId)) {
                        JOptionPane.showMessageDialog(BorrowPanel.this, "归还成功");
                        loadBorrows();
                    } else {
                        JOptionPane.showMessageDialog(BorrowPanel.this, "归还失败", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(BorrowPanel.this, "请先选择一条借阅记录", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        refreshButton.addActionListener(e -> loadBorrows());
    }

    // 加载所有借阅记录到表格
    private void loadBorrows() {
        tableModel.setRowCount(0);
        List<Borrow> borrows = borrowDAO.getAllBorrows();

        for (Borrow borrow : borrows) {
            Book book = bookDAO.getBookById(borrow.getBookId());
            Reader reader = readerDAO.getReaderById(borrow.getReaderId());

            if (book != null && reader != null) {
                Object[] row = {
                        borrow.getId(),
                        book.getId(),
                        book.getTitle(),
                        reader.getId(),
                        reader.getName(),
                        borrow.getBorrowDate(),
                        borrow.getDueDate(),
                        borrow.getReturnDate(),
                        borrow.isReturned() ? "已归还" : "借阅中"
                };
                tableModel.addRow(row);
            }
        }
    }

    // 显示借阅对话框
    private void showBorrowDialog() {
        JDialog dialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(this), "借阅图书", true);
        dialog.setSize(500, 200);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JComboBox<Book> bookComboBox = new JComboBox<>();
        JComboBox<Reader> readerComboBox = new JComboBox<>();
        JSpinner dueDateSpinner = new JSpinner(new SpinnerNumberModel(30, 7, 90, 1));

        // 加载图书列表
        List<Book> books = bookDAO.getAllBooks();
        for (Book book : books) {
            if (book.getStock() > 0) {
                bookComboBox.addItem(book);
            }
        }

        // 加载读者列表
        List<Reader> readers = readerDAO.getAllReaders();
        for (Reader reader : readers) {
            readerComboBox.addItem(reader);
        }

        panel.add(new JLabel("选择图书:"));
        panel.add(bookComboBox);
        panel.add(new JLabel("选择读者:"));
        panel.add(readerComboBox);
        panel.add(new JLabel("借阅天数:"));
        panel.add(dueDateSpinner);

        JPanel buttonPanel = new JPanel();
        JButton borrowButton = new JButton("确认借阅");
        JButton cancelButton = new JButton("取消");

        buttonPanel.add(borrowButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        borrowButton.addActionListener(e -> {
            if (bookComboBox.getItemCount() == 0) {
                JOptionPane.showMessageDialog(dialog, "没有可借阅的图书", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (readerComboBox.getItemCount() == 0) {
                JOptionPane.showMessageDialog(dialog, "没有可借阅的读者", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            Book selectedBook = (Book) bookComboBox.getSelectedItem();
            Reader selectedReader = (Reader) readerComboBox.getSelectedItem();
            int days = (int) dueDateSpinner.getValue();

            // 检查读者是否有未归还的图书
            List<Borrow> unreturnedBorrows = borrowDAO.getUnreturnedBorrowsByReader(selectedReader.getId());
            if (unreturnedBorrows.size() >= 3) {
                JOptionPane.showMessageDialog(dialog, "该读者已有3本未归还的图书，不能再借阅", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 检查图书库存
            if (selectedBook.getStock() <= 0) {
                JOptionPane.showMessageDialog(dialog, "该图书已无库存", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 创建借阅记录
            Calendar calendar = Calendar.getInstance();
            Date borrowDate = new Date(calendar.getTimeInMillis());

            calendar.add(Calendar.DAY_OF_MONTH, days);
            Date dueDate = new Date(calendar.getTimeInMillis());

            Borrow borrow = new Borrow(selectedBook.getId(), selectedReader.getId(), borrowDate, dueDate);

            if (borrowDAO.addBorrow(borrow)) {
                // 更新图书库存
                selectedBook.setStock(selectedBook.getStock() - 1);
                bookDAO.updateBook(selectedBook);

                JOptionPane.showMessageDialog(dialog, "借阅成功");
                dialog.dispose();
                loadBorrows();
            } else {
                JOptionPane.showMessageDialog(dialog, "借阅失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }
}